package com.block.risk.service.type;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.db.entity.MemberExtInfo;
import com.block.db.entity.RiskResultInfo;
import com.block.db.mapper.RiskResultInfoMapper;
import com.block.risk.model.param.RiskControlParam;
import com.block.risk.model.result.RiskControlResult;
import com.block.risk.model.result.RiskJudgeResult;
import com.block.risk.service.IRiskResultInfoService;
import com.block.risk.service.IRiskService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 载阳自己的风控 数据
 */
@Service
public class ZaiYang2RiskService implements IRiskService {

    private static Logger log = LogFactory.getRiskLog();

//    private List<String> valueListSelf = Arrays.asList("0", "(0,500)", "[500,1000)", "[1000,2000)", "[2000,3000)");
    private List<String> valueListSelf = Arrays.asList("0", "(0,500)", "[500,1000)");

    @Autowired
    IRiskResultInfoService riskResultInfoService;
    @Resource
    RiskResultInfoMapper riskResultInfoMapper;

    @Override
    public RiskControlResult riskHandlerExec(RiskControlParam riskParamInfo) {

        RiskControlResult controlResult = new RiskControlResult();
        controlResult.setSuccess(false);

        MemberExtInfo memberExtInfo = riskParamInfo.getMemberExtInfo();

        RiskResultInfo riskResultInfoQuery =  riskResultInfoMapper.getEntityByDataIdAndTypeAndUid(riskParamInfo.getDataId(), riskParamInfo.getDataType(), memberExtInfo.getUid());
        if (ObjectUtil.isNotEmpty(riskResultInfoQuery)){
            if (ObjectUtil.equals(Integer.valueOf(1), riskResultInfoQuery.getStatus())){
                // 风控查询不为空，且风控通过
                controlResult.setMessage("风控通过");
                controlResult.setSuccess(true);
            }else {
                // 风控查询不为空，且风控通过
                controlResult.setMessage(riskResultInfoQuery.getMessage());
            }
            return controlResult;
        }

        RiskResultInfo riskResultInfo = this.queryQuanJingResult(memberExtInfo, riskParamInfo);
        if (ObjectUtil.isEmpty(riskResultInfo)){
            controlResult.setMessage("风控结果为空");
            return controlResult;
        }

        if (ObjectUtil.equals(Integer.valueOf(0), riskResultInfo.getStatus())){
            controlResult.setMessage(riskResultInfo.getMessage());
            return controlResult;
        }

        controlResult.setSuccess(true);
        controlResult.setMessage("杭州载阳风控通过");
        return controlResult;
    }

    private RiskResultInfo queryQuanJingResult(MemberExtInfo memberExtInfo, RiskControlParam riskParamInfo){

        RiskResultInfo commonRiskResultInfo = riskResultInfoService.getCommonRiskResult(memberExtInfo, riskParamInfo.getRiskBaseInfo());
        if (ObjectUtil.isEmpty(commonRiskResultInfo)){
            return null;
        }

        RiskResultInfo updateEntity = new RiskResultInfo();
        updateEntity.setId(commonRiskResultInfo.getId());

        // 风控结果判断
        RiskJudgeResult riskJudgeResult = this.riskControlQuanJing(commonRiskResultInfo);
        updateEntity.setStatus(riskJudgeResult.isPass()?1:0);
        updateEntity.setMessage(riskJudgeResult.getResult());

        boolean save = riskResultInfoService.updateById(updateEntity);
        if (!save){
            return null;
        }
        return riskResultInfoService.getById(commonRiskResultInfo.getId());
    }

    private RiskJudgeResult riskControlQuanJing(RiskResultInfo riskResultInfo){
        RiskJudgeResult riskJudgeResult = new RiskJudgeResult();
        riskJudgeResult.setPass(false);

        if (!StrUtil.equals(riskResultInfo.getCode(), "0")){
            riskJudgeResult.setResult(riskResultInfo.getMessage());
            return riskJudgeResult;
        }

        String resultInfo = riskResultInfo.getResult();
        try {
            JSONObject jsonObject = JSON.parseObject(resultInfo);

            String code = jsonObject.getString("code");
            String desc = jsonObject.getString("desc");
            if (!StrUtil.equals(code, "0")){
                riskJudgeResult.setResult(desc);
                return riskJudgeResult;
            }

            JSONObject result_detail = jsonObject.getJSONObject("result_detail");
            if (ObjectUtil.isEmpty(result_detail)){
                riskJudgeResult.setResult("result_detail对象为空");
                return riskJudgeResult;
            }

            JSONObject currentReportDetail = result_detail.getJSONObject("current_report_detail");
            JSONObject behaviorReportDetail = result_detail.getJSONObject("behavior_report_detail");
            JSONObject applyReportDetail = result_detail.getJSONObject("apply_report_detail");

            if (ObjectUtil.isEmpty(behaviorReportDetail)){
                riskJudgeResult.setResult("行为数据结果为空；【behavior_report_detail】");
                return riskJudgeResult;
            }

            /**
             * 一个月内还款金额大于1000 六个月内逾期小于2
             */

            // B22170040 近1 个月履约贷款总金额
            String repayAmount = behaviorReportDetail.getString("B22170040");
            if (valueListSelf.contains(repayAmount)){
                riskJudgeResult.setResult(StrUtil.format("一个月还款款金额>1000不通过；【{}】", repayAmount));
                return riskJudgeResult;
            }

            /**
             * 近6 个月 MI+逾期贷款笔数
             */
            String numberSettle = behaviorReportDetail.getString("B22170028");
            if (Integer.valueOf(numberSettle) > 1){
                riskJudgeResult.setResult(StrUtil.format("近6 个月 MI+逾期贷款笔数小于2不通过；【{}】", numberSettle));
                return riskJudgeResult;
            }

            riskJudgeResult.setPass(true);
            riskJudgeResult.setResult(StrUtil.format("全景分控通过"));
            return riskJudgeResult;
        }catch (JSONException exception){
            exception.printStackTrace();
            riskJudgeResult.setResult("异常："+riskResultInfo.getResult());
        }
        return riskJudgeResult;
    }

}
